<template>
  <div class="chat-container">
    <!-- 会话列表 -->
    <div class="conversation-list" :style="{ width: conversationListWidth + 'px' }">
      <div class="conversation-header">
        <div class="search-box">
          <el-input v-model="searchKeyword" placeholder="搜索会话..." prefix-icon="Search" clearable size="small" />
        </div>
      </div>

      <div class="conversation-items">
        <transition-group name="conversation" tag="div">
          <div v-for="conversation in filteredConversations" :key="conversation.id" class="conversation-item fade-in"
            :class="{ 'active': activeConversationId === conversation.id }"
            @click="selectConversation(conversation.id)">
            <div class="avatar-wrapper">
              <el-avatar :size="48" :src="conversation.participantAvatar">
                {{ conversation.participantName.charAt(0) }}
              </el-avatar>
              <div class="online-indicator" :class="{ 'online': conversation.isOnline }" />
            </div>

            <div class="conversation-info">
              <div class="conversation-header-info">
                <span class="participant-name">{{ conversation.participantName }}</span>
                <span class="last-time">{{ formatTime(conversation.lastMessage?.timestamp) }}</span>
              </div>

              <div class="last-message">
                <span class="message-content">
                  {{ conversation.lastMessage?.content || '暂无消息' }}
                </span>
                <el-badge v-if="conversation.unreadCount > 0" :value="conversation.unreadCount" :max="99"
                  class="unread-badge" />
              </div>
            </div>
          </div>
        </transition-group>
      </div>
    </div>

    <!-- 拖拽分隔条 -->
    <div class="resize-handle" @mousedown="startResize" @dblclick="resetWidth">
      <div class="resize-line"></div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-area">
      <div v-if="!activeConversation" class="empty-chat">
        <el-icon :size="80" class="empty-icon">
          <ChatRound />
        </el-icon>
        <p class="empty-text">选择一个会话开始聊天</p>
      </div>

      <div v-else class="chat-content">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="chat-user-info">
            <el-avatar :size="40" :src="activeConversation.participantAvatar">
              {{ activeConversation.participantName.charAt(0) }}
            </el-avatar>
            <div class="user-details">
              <span class="user-name">{{ activeConversation.participantName }}</span>
              <span class="user-status">
                {{ activeConversation.isOnline ? '在线' : `最后在线: ${formatTime(activeConversation.lastSeen)}` }}
              </span>
            </div>
          </div>

          <div class="chat-actions">
            <el-button circle size="small" @click="showUserInfo">
              <el-icon>
                <User />
              </el-icon>
            </el-button>
            <el-button circle size="small" @click="clearChatHistory">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="message-list" ref="messageListRef">
          <div v-for="message in currentMessages" :key="message.id" class="message-item"
            :class="{ 'own-message': message.senderId === 'current-user' }">
            <div class="message-avatar">
              <el-avatar :size="36" :src="getMessageAvatar(message)">
                {{ getMessageSenderName(message).charAt(0) }}
              </el-avatar>
            </div>

            <div class="message-content">
              <div class="message-info">
                <span class="sender-name">{{ getMessageSenderName(message) }}</span>
                <span class="message-time">{{ formatTime(message.timestamp) }}</span>
              </div>

              <div class="message-bubble">
                <span class="message-text">{{ message.content }}</span>
                <div class="message-status">
                  <el-icon v-if="message.status === 'sending'" class="status-icon sending">
                    <Loading />
                  </el-icon>
                  <el-icon v-else-if="message.status === 'sent'" class="status-icon sent">
                    <Check />
                  </el-icon>
                  <el-icon v-else-if="message.status === 'delivered'" class="status-icon delivered">
                    <Check />
                  </el-icon>
                  <el-icon v-else-if="message.status === 'read'" class="status-icon read">
                    <Check />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 消息输入区 -->
        <div class="message-input-area">
          <div class="input-toolbar">
            <el-button circle size="small" @click="showEmojiPanel">
              <el-icon>
                <Sunny />
              </el-icon>
            </el-button>
            <el-button circle size="small" @click="selectFile">
              <el-icon>
                <Paperclip />
              </el-icon>
            </el-button>
            <el-button circle size="small" @click="selectImage">
              <el-icon>
                <Picture />
              </el-icon>
            </el-button>
          </div>

          <div class="input-box">
            <el-input v-model="messageInput" type="textarea" :rows="3" placeholder="输入消息..." resize="none"
              @keydown.enter.exact.prevent="sendMessage" @keydown.ctrl.enter.exact="messageInput += '\n'" />
          </div>

          <div class="input-actions">
            <span class="input-tip">按 Enter 发送，Ctrl+Enter 换行</span>
            <el-button type="primary" :disabled="!messageInput.trim()" @click="sendMessage">
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  ChatRound, User, Delete, Loading, Check,
  Sunny, Paperclip, Picture
} from '@element-plus/icons-vue'
import { useChatStore } from '@/stores/chat'
import { useUserStore } from '@/stores/counter'

const chatStore = useChatStore()
const userStore = useUserStore()

const searchKeyword = ref('')
const messageInput = ref('')
const messageListRef = ref<HTMLElement>()

// 拖拽调整宽度相关
const conversationListWidth = ref(320)
const isResizing = ref(false)
const minWidth = 250
const maxWidth = 500

// 计算属性
const activeConversationId = computed(() => chatStore.activeConversationId)
const activeConversation = computed(() => chatStore.activeConversation)
const currentMessages = computed(() => chatStore.currentMessages)

// 过滤会话列表
const filteredConversations = computed(() => {
  if (!searchKeyword.value.trim()) {
    return chatStore.conversations
  }

  const keyword = searchKeyword.value.toLowerCase()
  return chatStore.conversations.filter(conv =>
    conv.participantName.toLowerCase().includes(keyword) ||
    conv.lastMessage?.content.toLowerCase().includes(keyword)
  )
})

// 选择会话
const selectConversation = (conversationId: string) => {
  chatStore.setActiveConversation(conversationId)
}

// 发送消息
const sendMessage = () => {
  if (!messageInput.value.trim() || !activeConversation.value) return

  chatStore.sendMessage(
    messageInput.value.trim(),
    activeConversation.value.participantId
  )

  messageInput.value = ''
  scrollToBottom()
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight
    }
  })
}

// 格式化时间
const formatTime = (date?: Date) => {
  if (!date) return ''

  const now = new Date()
  const diff = now.getTime() - date.getTime()

  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`

  return date.toLocaleDateString()
}

// 获取消息发送者头像
const getMessageAvatar = (message: { senderId: string }) => {
  if (message.senderId === 'current-user') {
    return userStore.currentUser?.avatar || '/default-avatar.png'
  }
  return activeConversation.value?.participantAvatar || '/default-avatar.png'
}

// 获取消息发送者名称
const getMessageSenderName = (message: { senderId: string }) => {
  if (message.senderId === 'current-user') {
    return userStore.currentUser?.nickname || '我'
  }
  return activeConversation.value?.participantName || '对方'
}

// 显示用户信息
const showUserInfo = () => {
  ElMessage.info('用户信息功能开发中...')
}

// 清空聊天记录
const clearChatHistory = () => {
  if (activeConversationId.value) {
    chatStore.clearMessages(activeConversationId.value)
    ElMessage.success('聊天记录已清空')
  }
}

// 显示表情面板
const showEmojiPanel = () => {
  ElMessage.info('表情功能开发中...')
}

// 选择文件
const selectFile = () => {
  ElMessage.info('文件发送功能开发中...')
}

// 选择图片
const selectImage = () => {
  ElMessage.info('图片发送功能开发中...')
}

// 拖拽调整宽度相关方法
const startResize = (e: MouseEvent) => {
  isResizing.value = true
  document.addEventListener('mousemove', handleResize)
  document.addEventListener('mouseup', stopResize)
  document.body.style.cursor = 'col-resize'
  document.body.style.userSelect = 'none'
  e.preventDefault()
}

const handleResize = (e: MouseEvent) => {
  if (!isResizing.value) return

  const newWidth = e.clientX
  if (newWidth >= minWidth && newWidth <= maxWidth) {
    conversationListWidth.value = newWidth
  }
}

const stopResize = () => {
  isResizing.value = false
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
  document.body.style.cursor = ''
  document.body.style.userSelect = ''
}

const resetWidth = () => {
  conversationListWidth.value = 320
}

// 监听当前消息变化，自动滚动到底部
watch(currentMessages, () => {
  scrollToBottom()
}, { deep: true })

// 组件挂载时初始化数据
onMounted(() => {
  chatStore.initMockData()
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  if (isResizing.value) {
    stopResize()
  }
})
</script>

<style scoped lang="scss">
.chat-container {
  display: flex;
  height: 100vh;
  background: var(--bg-secondary);
}

.conversation-list {
  min-width: 250px;
  max-width: 500px;
  background: var(--bg-primary);
  border-right: 1px solid var(--border-light);
  display: flex;
  flex-direction: column;
  box-shadow: var(--shadow-md);
  transition: width 0.1s ease;

  .conversation-header {
    padding: var(--spacing-md);
    border-bottom: 1px solid var(--border-light);
    background: var(--bg-primary);

    .search-box {
      :deep(.el-input) {
        .el-input__wrapper {
          border-radius: var(--radius-full);
          background: var(--bg-secondary);
          border: 1px solid var(--border-light);
          box-shadow: var(--shadow-sm);
          transition: var(--transition-fast);

          &:hover {
            background: var(--bg-tertiary);
            border-color: var(--border-medium);
          }

          &.is-focus {
            background: var(--bg-primary);
            border-color: var(--primary-500);
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
          }

          .el-input__inner {
            color: var(--text-primary);

            &::placeholder {
              color: var(--text-tertiary);
            }
          }
        }
      }
    }
  }

  .conversation-items {
    flex: 1;
    overflow-y: auto;

    .conversation-item {
      display: flex;
      align-items: center;
      padding: var(--spacing-sm) var(--spacing-md);
      cursor: pointer;
      transition: var(--transition-fast);
      border-bottom: 1px solid var(--border-light);
      position: relative;

      &:hover {
        background: var(--bg-secondary);
      }

      &.active {
        background: linear-gradient(90deg, var(--primary-50) 0%, var(--primary-100) 100%);
        border-right: 3px solid var(--primary-500);

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 0;
          bottom: 0;
          width: 3px;
          background: var(--primary-500);
        }
      }

      .avatar-wrapper {
        position: relative;
        margin-right: var(--spacing-sm);

        .online-indicator {
          position: absolute;
          bottom: 2px;
          right: 2px;
          width: 12px;
          height: 12px;
          border-radius: var(--radius-full);
          background: var(--gray-400);
          border: 2px solid var(--bg-primary);
          box-shadow: var(--shadow-sm);

          &.online {
            background: var(--success-500);
          }
        }
      }

      .conversation-info {
        flex: 1;
        min-width: 0;

        .conversation-header-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: var(--spacing-xs);

          .participant-name {
            font-weight: var(--font-medium);
            color: var(--text-primary);
            font-size: var(--text-sm);
          }

          .last-time {
            font-size: var(--text-xs);
            color: var(--text-tertiary);
            font-weight: var(--font-medium);
          }
        }

        .last-message {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .message-content {
            flex: 1;
            font-size: var(--text-xs);
            color: var(--text-secondary);
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            line-height: var(--leading-tight);
          }

          .unread-badge {
            margin-left: var(--spacing-sm);

            :deep(.el-badge__content) {
              background: var(--primary-500);
              border: none;
              font-size: 10px;
              font-weight: var(--font-semibold);
              min-width: 18px;
              height: 18px;
              line-height: 16px;
            }
          }
        }
      }
    }
  }
}

// 拖拽分隔条样式
.resize-handle {
  width: 4px;
  background: transparent;
  cursor: col-resize;
  position: relative;
  flex-shrink: 0;
  transition: background-color 0.2s ease;

  &:hover {
    background: var(--primary-200);

    .resize-line {
      opacity: 1;
      background: var(--primary-500);
    }
  }

  &:active {
    background: var(--primary-300);
  }

  .resize-line {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 2px;
    height: 40px;
    background: var(--border-medium);
    border-radius: var(--radius-full);
    opacity: 0.6;
    transition: all 0.2s ease;
  }
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--bg-primary);

  .empty-chat {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: var(--text-tertiary);
    background: var(--bg-secondary);

    .empty-icon {
      margin-bottom: var(--spacing-md);
      opacity: 0.6;
      color: var(--text-tertiary);
    }

    .empty-text {
      font-size: var(--text-lg);
      font-weight: var(--font-medium);
      margin: 0;
    }
  }

  .chat-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: var(--bg-primary);

    .chat-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: var(--spacing-md) var(--spacing-lg);
      border-bottom: 1px solid var(--border-light);
      background: var(--bg-primary);
      box-shadow: var(--shadow-sm);

      .chat-user-info {
        display: flex;
        align-items: center;

        .user-details {
          margin-left: var(--spacing-sm);

          .user-name {
            display: block;
            font-weight: var(--font-semibold);
            color: var(--text-primary);
            font-size: var(--text-base);
            line-height: var(--leading-tight);
          }

          .user-status {
            display: block;
            font-size: var(--text-xs);
            color: var(--text-secondary);
            margin-top: var(--spacing-xs);
            font-weight: var(--font-medium);
          }
        }
      }

      .chat-actions {
        display: flex;
        gap: var(--spacing-sm);

        .el-button {
          border: 1px solid var(--border-light);
          background: var(--bg-secondary);
          color: var(--text-secondary);
          transition: var(--transition-fast);

          &:hover {
            border-color: var(--primary-500);
            background: var(--primary-50);
            color: var(--primary-600);
          }
        }
      }
    }

    .message-list {
      flex: 1;
      overflow-y: auto;
      padding: var(--spacing-md) var(--spacing-lg);
      background: var(--bg-secondary);

      .message-item {
        display: flex;
        margin-bottom: var(--spacing-md);
        animation: slideUp 0.3s ease-out;

        &.own-message {
          flex-direction: row-reverse;

          .message-content {
            align-items: flex-end;

            .message-info {
              text-align: right;
            }

            .message-bubble {
              background: linear-gradient(135deg, var(--primary-500) 0%, var(--primary-600) 100%);
              color: var(--text-inverse);
              box-shadow: var(--shadow-md);

              .message-status {
                .status-icon {
                  color: rgba(255, 255, 255, 0.8);

                  &.read {
                    color: var(--success-300);
                  }
                }
              }
            }
          }

          .message-avatar {
            margin-left: var(--spacing-sm);
            margin-right: 0;
          }
        }

        .message-avatar {
          margin-right: var(--spacing-sm);
        }

        .message-content {
          display: flex;
          flex-direction: column;
          max-width: 60%;

          .message-info {
            display: flex;
            align-items: center;
            gap: var(--spacing-sm);
            margin-bottom: var(--spacing-xs);

            .sender-name {
              font-size: var(--text-xs);
              color: var(--text-secondary);
              font-weight: var(--font-medium);
            }

            .message-time {
              font-size: 11px;
              color: var(--text-tertiary);
              font-weight: var(--font-medium);
            }
          }

          .message-bubble {
            position: relative;
            background: var(--bg-primary);
            border-radius: var(--radius-lg);
            padding: var(--spacing-sm) var(--spacing-md);
            box-shadow: var(--shadow-sm);
            word-wrap: break-word;
            border: 1px solid var(--border-light);

            .message-text {
              line-height: var(--leading-normal);
              font-size: var(--text-sm);
              color: inherit;
            }

            .message-status {
              position: absolute;
              bottom: var(--spacing-xs);
              right: var(--spacing-sm);

              .status-icon {
                font-size: 12px;

                &.sending {
                  color: var(--warning-500);
                  animation: spin 1s linear infinite;
                }

                &.sent {
                  color: var(--text-tertiary);
                }

                &.delivered {
                  color: var(--primary-500);
                }

                &.read {
                  color: var(--success-500);
                }
              }
            }
          }
        }
      }
    }

    .message-input-area {
      border-top: 1px solid var(--border-light);
      background: var(--bg-primary);
      padding: var(--spacing-md) var(--spacing-lg);
      box-shadow: var(--shadow-sm);

      .input-toolbar {
        display: flex;
        gap: var(--spacing-sm);
        margin-bottom: var(--spacing-sm);

        .el-button {
          border: 1px solid var(--border-light);
          background: var(--bg-secondary);
          color: var(--text-secondary);
          transition: var(--transition-fast);

          &:hover {
            border-color: var(--primary-500);
            background: var(--primary-50);
            color: var(--primary-600);
          }
        }
      }

      .input-box {
        margin-bottom: var(--spacing-sm);

        :deep(.el-textarea) {
          .el-textarea__inner {
            border-radius: var(--radius-md);
            border: 1px solid var(--border-medium);
            resize: none;
            font-family: inherit;
            background: var(--bg-secondary);
            transition: var(--transition-fast);

            &:focus {
              border-color: var(--primary-500);
              box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
              background: var(--bg-primary);
            }

            &::placeholder {
              color: var(--text-tertiary);
            }
          }
        }
      }

      .input-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .input-tip {
          font-size: var(--text-xs);
          color: var(--text-tertiary);
          font-weight: var(--font-medium);
        }

        .el-button {
          background: linear-gradient(135deg, var(--primary-500) 0%, var(--primary-600) 100%);
          border: none;
          color: var(--text-inverse);
          font-weight: var(--font-semibold);
          box-shadow: var(--shadow-sm);

          &:hover:not(:disabled) {
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
          }

          &:disabled {
            opacity: 0.5;
            transform: none;
          }
        }
      }
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

// 过渡动画
.conversation-enter-active,
.conversation-leave-active {
  transition: all 0.3s ease;
}

.conversation-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.conversation-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

.conversation-move {
  transition: transform 0.3s ease;
}
</style>
